﻿using Hinacom.Scheduler;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;

namespace Hinacom.Scheduler.Jobs.SimpleJobs
{
    [JobParameter(Type = typeof(FileCleanupJobParameter))]
    public class FileCleanupJob : SchedulerJob
    {
        protected override void Execute(SchedulerJobExecutionContext context)
        {
            context.ExecutionLog.AppendLine("Analyzing paramters...");

            FileCleanupJobParameter parameter = new FileCleanupJobParameter(context.Parameter);
            FileCleanupContext cleanupContext = null;
            if (ValidateParameter(parameter, context.ExecutionLog, out cleanupContext))
                return;

            DirectoryInfo dir = new DirectoryInfo(parameter.BaseDirectory);
            cleanupContext.BaseDirectory = dir.FullName;

            context.ExecutionLog.AppendLine(String.Format("Base directory: {0}.", cleanupContext.BaseDirectory));
            if (cleanupContext.EnableBackup)
                context.ExecutionLog.AppendLine(String.Format("Backup enabled, root: \"{0}\".", cleanupContext.BackupRoot));
            context.ExecutionLog.AppendLine(String.Format("Files not being accessed since {0} are regarded expired.", cleanupContext.TimeOfExpiration.ToString(StandardUtcTimeFormatForLog)));

            foreach (string searchPattern in parameter.FileSearchPatterns)
            {
                context.ExecutionLog.AppendFormat("Searching for files \"{0}\" {1}... ",
                    searchPattern,
                    parameter.SearchChildDirecotories ? "recursively" : "in direct children");

                FileInfo[] files = dir.GetFiles(searchPattern, parameter.SearchChildDirecotories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                context.ExecutionLog.AppendLine(String.Format("{0} file(s) found.", files.Length.ToString()));

                foreach (FileInfo file in files)
                {
                    ProcessSingleFile(file, cleanupContext, context.ExecutionLog);
                }
            }

            context.ExecutionLog.AppendLine(String.Format("Cleaning completed. {0} file(s) were cleaned. {1} file(s) were failed to be cleaned.",
                cleanupContext.NumberFileCleaned.ToString(), cleanupContext.NumberCleanningFailed.ToString()));
        }

        private bool ValidateParameter(FileCleanupJobParameter parameter, StringBuilder executionLog, out FileCleanupContext cleanupContext)
        {
            cleanupContext = new FileCleanupContext();

            if (String.IsNullOrWhiteSpace(parameter.BaseDirectory) || !Directory.Exists(parameter.BaseDirectory))
            {
                executionLog.AppendLine("Invalid parameter: Base directory is not provided. Execution terminated.");
                return false;
            }

            if (!parameter.ExpirationPeriod.HasValue)
            {
                executionLog.AppendLine("Invalid parameter: Expiration time is not provided. Execution terminated.");
                return false;
            }

            if (!String.IsNullOrWhiteSpace(parameter.BackupBaseDirectory))
            {
                cleanupContext.EnableBackup = true;
                cleanupContext.BackupRoot = Path.Combine(parameter.BackupBaseDirectory, DateTime.Now.ToString(parameter.BackupFolderFormat));
            }

            cleanupContext.TimeOfExpiration = DateTime.UtcNow.Add(parameter.ExpirationPeriod.Value.Negate());

            return true;
        }

        private string GetRelativePath(string baseDirectory, string filePath)
        {
            string relativePath = null;
            if (filePath.ToLower().StartsWith(baseDirectory))
            {
                relativePath = filePath.Substring(baseDirectory.Length);
                if (relativePath.StartsWith("\\"))
                    relativePath = relativePath.Substring(1);
            }
            return relativePath;
        }

        private void ProcessSingleFile(FileInfo file, FileCleanupContext cleanupContext, StringBuilder executionLog)
        {
            if (file.LastAccessTimeUtc < cleanupContext.TimeOfExpiration)
            {
                string relativePath = GetRelativePath(cleanupContext.BaseDirectory.ToLower(), file.FullName.ToLower());
                if (relativePath == null)
                {
                    ++cleanupContext.NumberCleanningFailed;
                    executionLog.AppendLine(String.Format("File \"{0}\" was ignored for its relative path cannot be resolved.", file.FullName));
                    return;
                }

                if (!cleanupContext.EnableBackup)
                {
                    try
                    {
                        file.Delete();
                        ++cleanupContext.NumberFileCleaned;
                        executionLog.AppendLine(String.Format("File \"{0}\" is deleted.", relativePath));
                    }
                    catch (Exception ex)
                    {
                        ++cleanupContext.NumberCleanningFailed;
                        executionLog.AppendLine(String.Format("Failed to delete file \"{0}\" due to an error. Details", relativePath));
                        executionLog.AppendLine(GenerateErrorLog(ex));
                    }
                }
                else
                {
                    string targetFile = Path.Combine(cleanupContext.BackupRoot, relativePath);
                    string targetDir = Path.GetDirectoryName(targetFile);
                    try
                    {
                        if (!Directory.Exists(targetDir))
                            Directory.CreateDirectory(targetDir);
                        file.CopyTo(targetFile);
                        file.Delete();
                        ++cleanupContext.NumberFileCleaned;
                        executionLog.AppendLine(String.Format("File \"{0}\" is deleted. Backup created at \"{1}\"", relativePath, targetFile));
                    }
                    catch (Exception ex)
                    {
                        ++cleanupContext.NumberCleanningFailed;
                        executionLog.AppendLine(String.Format("Failed to process file \"{0}\" (backup \"{1}\") due to an error. Details", relativePath, targetFile));
                        executionLog.AppendLine(GenerateErrorLog(ex));
                    }
                }
            }
        }
             

        private class FileCleanupContext
        {
            public string BaseDirectory { get; set; }
            public bool EnableBackup { get; set; }
            public string BackupRoot { get; set; }
            public DateTime TimeOfExpiration { get; set; }
            public int NumberFileCleaned { get; set; }
            public int NumberCleanningFailed { get; set; }
        }

    }

    public class FileCleanupJobParameter: JobParameter
    {
        public FileCleanupJobParameter() : base() { }
        public FileCleanupJobParameter(IDictionary<string, object> source) : base(source) { }

        [JobParameterDataItemKey("BaseDirectory")]
        [Description("进行清理的根目录。")]
        public string BaseDirectory
        {
            get
            {
                return (base["BaseDirectory"] as string ?? "").Trim();
            }
            set
            {
                base["BaseDirectory"] = value;
            }
        }
        [JobParameterDataItemKey("FileSearchPattern")]
        [Description("用来搜索文件的关键字。如*.log。")]
        public string[] FileSearchPatterns
        {
            get
            {
                string pattern = base["FileSearchPattern"] as string;
                if (pattern == null)
                    return new string[] { "*" };
                string[] ps = pattern.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.Trim()) // trim
                    .Where(s => !String.IsNullOrEmpty(s)) // remove empty
                    .ToArray();
                if (ps.Length == 0)
                    return new string[] { "*" };
                return ps;
            }
            set
            {
                if (value == null)
                    base["FileSearchPattern"] = null;
                else
                    base["FileSearchPattern"] = String.Join(",", value);
            }
        }
        [JobParameterDataItemKey("SearchChildDirecotories")]
        [DefaultValue(false)]
        [Description("搜索时是否搜索子目录。")]
        public bool SearchChildDirecotories
        {
            get
            {
                object b = base["SearchChildDirecotories"];
                if (b == null) return false;
                return (bool)b;
            }
            set
            {
                base["SearchChildDirecotories"] = value;
            }
        }
        [JobParameterDataItemKey("ExpirationTicks")]
        [Description("超过此时间未被访问过的文件视为过期。")]
        public TimeSpan? ExpirationPeriod
        {
            get
            {
                object ticks = base["ExpirationTicks"];
                if (ticks == null) return null;
                return new TimeSpan((long)ticks);
            }
            set
            {
                if (value.HasValue)
                    base["ExpirationTicks"] = value.Value.Ticks;
                else
                    base.Remove("ExpirationTicks");
            }
        }
        [JobParameterDataItemKey("BackupBaseDirectory")]
        [Description("指定文件备份的根目录。如不指定则不备份，直接删除过期文件。")]
        public string BackupBaseDirectory
        {
            get { return base["BackupBaseDirectory"] as string; }
            set { base["BackupBaseDirectory"] = value; }
        }
        [JobParameterDataItemKey("BackupFolderFormat")]
        [DefaultValue("'FileBackup 'yyyy'_'MM'_'dd' 'HH'_'mm'_'ss")]
        [Description("每次清理产生的备份会保存在根目录下的一个单独文件夹下以避免相互影响。这个字符串指定该文件夹生成的格式。必须为有效的DateTimeFormat字符串。")]
        public string BackupFolderFormat
        {
            get
            {
                string format = base["BackupFolderFormat"] as string;
                if (String.IsNullOrWhiteSpace(format))
                    return "'FileBackup 'yyyy'_'MM'_'dd' 'HH'_'mm'_'ss";
                return format;
            }
            set
            {
                base["BackupFolderFormat"] = value;
            }
        }
    }

}
